import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import date, timedelta
import Animation
def find_max_min(arr):
    if max(arr) > abs(min(arr)):
        return arr / max(arr)

    else:
        return arr / abs(min(arr))
def Velocity_3d_picture(x, y, z, begin, end, step, df_V, count):

    for i in range(1, step + 1):
        # x1 = find_max_min(x[begin + (i - 1) * 512:begin + i * 512])
        # y1 = find_max_min(y[begin + (i - 1) * 512:begin + i * 512])
        # z1 = find_max_min(z[begin + (i - 1) * 512:begin + i * 512])

        x1 = x[begin:end]
        y1 = y[begin:end]
        z1 = z[begin:end]
        fig = plt.figure(figsize=(10, 10))
        ax = fig.add_subplot(projection='3d')
        ax.scatter(x1, y1, z1, c='black', marker=">", s=10)

        date_begin = date(2023, 1, 1) + timedelta(days=df_V.iloc[begin + (i - 1) * count]["Day"]-1)
        date_end = date(2023, 1, 1) + timedelta(days=df_V.iloc[begin + (i) * count]["Day"] - 1)

        plt.title("Days: " + str(date_begin) +" : " + str(date_end) + " Hour: " + str(df_V.iloc[begin + (i - 1) * count]["Hour"]) + " - " + str(df_V.iloc[begin - 1 + (i) * count]["Hour"]), size=20,  weight="bold")

        #plt.suptitle(str(count)+"  Days №"+str(df_V.iloc[begin + (i - 1) * count]["Day"]) + " - " + str(df_V.iloc[begin + (i) * count]["Day"] ))
        ax.text2D(0.95, 0.05, "[km/s]", size = 20,  transform=ax.transAxes)
        plt.xlabel('$Vx$', size=32, color='black', labelpad=25)
        ax.tick_params(axis="x", labelsize=24)
        plt.ylabel('$Vy$', size=32, color='black', labelpad=25)
        ax.tick_params(axis="y", labelsize=24)
        ax.set_zlabel('$Vz$', size=32, labelpad=25)
        ax.tick_params(axis="z", labelsize=24)

        #ax.view_init(30, -126)  # изменение угла 3d графика
        #plt.savefig(f"/home/kmg/git/TFTB_GUIproject/Figure/diagram_{i}.png", dpi=300)
        plt.show()

    #Animation.animation_rotate(x1,y1,z1)

def V_Diagrams(df, begin, end, numb):
    X = df["Vx_GSE"]
    Y = df["Vy_GSE"]
    Z = df["Vz_GSE"]

    count = end - begin  # 720 # шаг по 3 часа для 15сек
    step = (end - begin) // count

    Velocity_3d_picture(X, Y, Z, begin, end, step, df, count)
    #velocity_rotation(X[begin:end], Y[begin:end], Z[begin:end], begin, step, 5760)

def Read_V_Table(file):
    arr = ["Year", "Day", "Hour", "Minute", "Vx_GSE", "Vy_GSE", "Vz_GSE"]
    df = pd.read_table(file, names=arr, sep="\s+")
    for i in arr:
        df.loc[(df[i] > 9999)] = None
    return df
